package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
	@Autowired
	private UserService userService;
	@PostMapping("/sendMsg")
	public R<String> sendMsg(@RequestBody User user, HttpSession session){
		//1.获取手机号
		String phone = user.getPhone();
		//2.生成四位字符串验证码
		String code = ValidateCodeUtils.generateValidateCode4String(4);
		//3.模拟发送验证码，在控制台显示验证码
		log.info("验证码={}",code);
		//4.将验证码保存刀session
		session.setAttribute(phone,code);
		return R.success("发送成功");
	}

	@PostMapping("/login")
	public R<String> login(@RequestBody Map map,HttpSession session){
		//1.获取前端窗体的手机号和验证码
		String phone = (String) map.get("phone");
		String code = (String) map.get("code");
		//2.从session中获取手机号对应的正确的验证码
		String codeForSession = (String) session.getAttribute(phone);
		//3.进行验证码的比对
		if (codeForSession!=null && codeForSession.equals(code)){
			LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
			queryWrapper.eq(User::getPhone,phone);
			User user = userService.getOne(queryWrapper);
			if (user==null){
				user = new User();
				user.setPhone(phone);
				user.setStatus(1);
				userService.save(user);
			}
			session.setAttribute("user",user.getId());
			return R.success("登录成功");
		}
		return R.error("验证码错误");
	}
	@PostMapping("/loginout")
	public R<String> loginout(HttpSession session){
		log.info("退出");
		session.invalidate();
		return R.success("成功退出");
	}
}
